/*
 * jngc, Java utility classes by Nicholas Coltharp
 * Copyright (C) 2010 Nicholas Coltharp <ngc1@rice.edu>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.rice.ngc1.util.iterable;

import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An {@code Iterable} which combines multiple {@code Iterable}s
 * together so that they can easily be iterated over simultaneously.
 * This is especially useful for iterating over a {@link Collection}
 * and a {@link Range} based on its length at the same time.
 */
public final class Zip implements Iterable<Object[]> {

    private final Iterable<?>[] iterables;

    public Zip(Iterable<?>... iterables) {
        this.iterables = new Iterable<?>[iterables.length];
        System.arraycopy(iterables, 0, this.iterables, 0, iterables.length);
    }

    @Override
    public Iterator<Object[]> iterator() {
        return new Iterator<Object[]>() {

            private final Iterator<?>[] iterators;
            {
                iterators = new Iterator<?>[iterables.length];
                for (int i : new Range(iterables.length)) {
                    iterators[i] = iterables[i].iterator();
                }
            }

            @Override
            public boolean hasNext() {
                if (iterators.length == 0) {
                    return false;
                }
                for (Iterator<?> iter : iterators) {
                    if (!iter.hasNext()) {
                        return false;
                    }
                }
                return true;
            }

            @Override
            public Object[] next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                Object[] results = new Object[iterators.length];
                for (int i : new Range(iterators.length)) {
                    results[i] = iterators[i].next();
                }
                return results;
            }

            @Override
            public void remove() {
                for (Iterator<?> iter : iterators) {
                    iter.remove();
                }
            }
        };
    }
}
